<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">

    <title>state</title>
</head>

<body>
    <h1>state</h1>
    <ol>
        <li>使用state不能使用无状态组件</li>
        <li>使用state需要在构造方法中初始化</li>
        <li>调用setState({key:value})来设置state的新值</li>
    </ol>
    <hr />
    <div id="demoReact"></div>
    <script src="../../node_modules/babel-standalone/babel.min.js"></script>
    <script src="../../node_modules/react/umd/react.development.js"></script>
    <script src="../../node_modules/react-dom/umd/react-dom.development.js"></script>
    <script type="text/babel">

        class MyCom extends React.Component {

            // 在ES6中，不管子类写不写constructor，new的时候都会补上constructor
            // 我们可以不写，但是我们写了，必须写上super()，作用是调用父类构造方法
            // 如果想在constructor中使用props那么必须写上super(props)
            constructor(props) {
                super(props)

                // 初始化state
                this.state = {
                    count: 0
                }
            }

            render() {
                return (
                    <div>
                        <button onClick={() => { this.setState({ count: this.state.count + 1 }) }}>点击自增</button>
                        <div>{this.state.count}</div>
                        <SubCom count={this.state.count}/>
                    </div>
                )
            }
        }

        class SubCom extends React.Component {

            constructor(props) {
                super(props)

                // 初始化state
                this.state = {
                    count: 0
                }
            }

            handleClick = () => {
                this.setState((prevState, props) => {
                    console.log("prevState = ",prevState);
                    console.log("props = ",props);
                    return {count: prevState.count + props.count};
                } )
            }

            render() {
                return (
                    <div>
                        <div>{this.state.count}</div>
                        <button onClick={this.handleClick}>更新</button>
                    </div>
                )
            }
        }

        // 创建根节点
        let root = ReactDOM.createRoot(document.getElementById("demoReact"));

        // 渲染组件
        root.render(<MyCom />);

    </script>
</body>

</html>